<template>
  <!-- 课程管理 -->
  <!-- 杨友朋 -->
  <div style="font-family:微软雅黑;padding:20px">
    <el-button @click="goxiang">详情</el-button>
      <div style="float: left; width: 1000px; margin-bottom: 20px">
        <el-select v-model="subjectId" placeholder="请选择科目" style="margin-right: 10px; width: 150px">
          <el-option v-for="item in subjectArr" :key="item.subjectType" :label="item.subjectType" :value="item.id"></el-option>
        </el-select>
        <el-select v-model="teacherId" placeholder="请选择教师" style="margin-right: 10px; width: 150px">
          <el-option v-for="item in teacherArr" :key="item.tname" :label="item.tname" :value="item.id"></el-option>
        </el-select>
        <el-select v-model="payType" placeholder="请选择付费类型" style="margin-right: 10px; width: 180px">
          <el-option v-for="item in payTypeArr" :key="item.label" :label="item.label" :value="item.id">
                     
          </el-option>
        </el-select>
        <el-select v-model="courseStatus" placeholder="请选择课程状态" style="margin-right: 10px; width: 180px">
          <el-option v-for="item in courseStatusArr" :key="item.label" :label="item.label" :value="item.id">
                     
          </el-option>
        </el-select>
        <el-input placeholder="请输入标题" v-model="courseTitle" style="width: 300px">
          <el-button slot="append" icon="el-icon-search" @click="selectCourse()"></el-button>
        </el-input>
        <div style="float: left; margin-top: 15px">
          <el-button type="primary" @click="add()" size="small" style="width: 80px">添加</el-button>
          <el-popconfirm confirm-button-text="确定" cancel-button-text="我再想想" icon="el-icon-info" icon-color="red" title="您确定删除吗？" @confirm="delBetch">
            <el-button type="primary" size="small" slot="reference" style="margin-left: 5px">批量删除</el-button>
          </el-popconfirm>
          <el-popconfirm confirm-button-text="确定" cancel-button-text="我再想想" icon="el-icon-info" icon-color="red" title="您确定上架吗？" @confirm="onShelf">
            <el-button type="primary" size="small" slot="reference" style="margin-left: 5px">批量上架</el-button>
          </el-popconfirm>
          <el-popconfirm confirm-button-text="确定" cancel-button-text="我再想想" icon="el-icon-info" icon-color="red" title="您确定下架吗？" @confirm="offShelf">
            <el-button type="primary" size="small" slot="reference" style="margin-left: 5px">批量下架</el-button>
          </el-popconfirm>
        </div>
      </div>
      <div style="background-color: white; margin-top: 20px"></div>
      <div style="background-color: white; margin-top: 10px">
        <!-- 全查 -->
        <el-table :data="courseData" style="width: 100%; margin-top: 10px; margin-left: 15px" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="课程封面图片" width="" align="center">
            <template slot-scope="scope">
              <el-image style="width: 112px; height: 70px" :src="
                  'http://101.43.223.224:8765/image/getImageById?id=' +
                  scope.row.imageId
                ">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="courseTitle" label="课程标题" align="center">
          </el-table-column>
          <el-table-column prop="introduction" label="课程介绍" align="center">
          </el-table-column>

          <el-table-column prop="subjectType" label="父级科目类型" align="center">
          </el-table-column>
          <el-table-column prop="tname" label="教师姓名" align="center">
          </el-table-column>
          <el-table-column label="课程状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.courseStatus == '0'">已上架</span>
              <span v-if="scope.row.courseStatus == '1'">已下架</span>
              <span v-if="scope.row.courseStatus == '2'">待上架</span>
            </template>
          </el-table-column>
          <el-table-column label="收费类型" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.payType == '0'">免费</span>
              <span v-if="scope.row.payType == '1'">付费</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="350px" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="upStatusById(scope.row)" v-if="scope.row.courseStatus == 0">下架</el-button>
              <el-button type="primary" size="small" @click="upStatusById(scope.row)" v-if="scope.row.courseStatus != 0">上架</el-button>
              <el-button @click="openUpCourse(scope.row)" type="primary" size="small">修改</el-button>
              <el-button type="primary" size="small" slot="reference" @click="del(scope.row.id)">删除</el-button>
              <el-button @click="goxiang(scope.row)" type="primary" size="small">查看章节</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination :page-sizes="[5, 10, 15, 20]" :page-size="pages.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pages.total" background :current-page.sync="pages.pageNum"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
        <div style="height: 10px"></div>
      </div>
      <div style="height:500px"></div>
      <el-dialog :visible.sync="unit" width="50%">
        <div slot="title" class="header-title" style="text-align: left; font-weight: bold; color: white; font-size: 18px; margin-bottom: 10px;">
          课程章节
        </div>
        <div style="float: left; width: 150px; margin-bottom: 20px">
          <el-button @click="openUnitAdd()" type="primary" size="small">添加章节</el-button>
        </div>
        <el-table :data="unitData" style="width: 100%; margin-top: 10px; margin-left: 15px" @selection-change="handleSelectionChange" show-overflow-tooltip default-expand-all row-key="id" stripe lazyb
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="序号" align="center" width="55">
          </el-table-column>
          <el-table-column prop="unitName" label="章节名称" align="center">
          </el-table-column>
          <el-table-column prop="unitIntroduction" label="章节介绍" align="center">
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="openJointAdd(scope.row)">新增课程</el-button>
              <el-button type="primary" size="small" @click="openJoint(scope.row)">查看课程</el-button>
              <el-button type="primary" size="small" slot="reference" @click="delUnit(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <el-dialog :visible.sync="joint" width="80%">
        <div slot="title" class="header-title" style="
            text-align: left;
            font-weight: bold;
            color: white;
            font-size: 18px;
            margin-bottom: 10px;
          ">
          章节详细课程
        </div>
        <el-table :data="jointData" style="width: 100%; margin-top: 10px; margin-left: 15px" @selection-change="handleSelectionChange" show-overflow-tooltip default-expand-all row-key="id" stripe
          lazyb :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="序号" align="center" width="55">
          </el-table-column>
          <el-table-column prop="jointTitle" label="课程标题" align="center">
          </el-table-column>
          <el-table-column prop="jointIntroduction" label="课程介绍" align="center">
          </el-table-column>
          <el-table-column prop="videoId" label="视频" align="center">
            <template slot-scope="scope">
              <div v-if="!scope.row.videoId">
                <p>暂无视频</p>
              </div>
              <div v-else class="video-wrapper">
                <video controls loop :src="'http://127.0.0.1:8088/video/getVideoById?id=' + scope.row.videoId"></video>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="jointStatus" label="课程状态" align="center">
            <template slot-scope="scope">
              <el-switch style="display: block" v-model="scope.row.jointStatus" active-color="#13ce66" inactive-color="#ff4949" active-text="启用" inactive-text="禁用" active-value="0" inactive-value="1"
                @change="upSwith(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="small" slot="reference" style="margin-left: 5px" @click="openUpJoint(scope.row)">修改</el-button>
              <el-popconfirm confirm-button-text="确定" cancel-button-text="我再想想" icon="el-icon-info" icon-color="red" title="您确定删除吗？" @confirm="delOne(scope.row.id)">
                <el-button type="primary" size="small" slot="reference" style="margin-left: 5px">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <!-- 添加章节 -->
      <el-dialog :visible.sync="unitAdd" width="20%">
        <div slot="title" class="header-title" style="
            text-align: left;
            font-weight: bold;
            color: white;
            font-size: 18px;
            margin-bottom: 10px;
          ">
          添加章节
        </div>
        <el-form stripe style="width: 100%" :model="unitForm" ref="jointForm">
          <el-form-item>
            <el-input v-model="unitForm.unitName" placeholder="请输入课程标题"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="unitForm.unitIntroduction" placeholder="请输入课程介绍"></el-input>
          </el-form-item>
        </el-form>
        <el-button style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)" @click="addUnit()">确 定</el-button>
        <el-button @click="addHandle = false" style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)">取 消</el-button>
      </el-dialog>

      <!-- 修改详细课程 -->
      <el-dialog :visible.sync="upJoint123" width="30%">
        <div slot="title" class="header-title" style="
            text-align: left;
            font-weight: bold;
            color: white;
            font-size: 18px;
            margin-bottom: 10px;
          ">
          修改详细课程
        </div>
        <el-form stripe style="width: 100%" :model="upJointForm" ref="upJointForm">
          <el-form-item label="标题">
            <el-input v-model="upJointForm.jointTitle" placeholder="请输入课程标题"></el-input>
          </el-form-item>
          <el-form-item label="介绍">
            <el-input v-model="upJointForm.jointIntroduction" placeholder="请输入课程介绍"></el-input>
          </el-form-item>
          <el-form-item label="上传视频">
          <br>
            <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" :on-change="handleChange" :http-request="putinMirror" :show-file-list="false">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <video controls loop :src="'http://127.0.0.1:8088/video/getVideoById?id=' + this.videoId" style="width:500px"></video>
          </el-form-item>
        </el-form>
        <el-button style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)" @click="upJoint()">确 定</el-button>
        <el-button @click="closeUpJoint()" style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)">取 消</el-button>
      </el-dialog>

      <!-- 添加详细课程 -->
      <el-dialog :visible.sync="jointAdd" width="20%">
        <div slot="title" class="header-title" style="
            text-align: left;
            font-weight: bold;
            color: white;
            font-size: 18px;
            margin-bottom: 10px;
          ">
          添加详细课程
        </div>
        <el-form stripe style="width: 100%" :model="jointForm" ref="jointForm">
          <el-form-item>
            <el-input v-model="jointForm.jointTitle" placeholder="请输入课程标题"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="jointForm.jointIntroduction" placeholder="请输入课程介绍"></el-input>
          </el-form-item>
          <el-form-item>
            <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" :on-change="handleChange" :http-request="putinMirror" :show-file-list="false">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <video controls loop :src="'http://127.0.0.1:8088/video/getVideoById?id=' + this.videoId" style="width:500px"></video>
          </el-form-item>
        </el-form>
        <el-button style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)" @click="addJoint()">确 定</el-button>
        <el-button @click="addHandle = false" style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)">取 消</el-button>
      </el-dialog>

      <!-- 添加课程 -->
      <el-dialog :visible.sync="addHandle" width="30%" style="text-align: left">
        <div slot="title" class="header-title" style="
            text-align: left;
            font-weight: bold;
            color: white;
            font-size: 18px;
            margin-bottom: 10px;
          ">
          课程添加
        </div>
        <el-form stripe style="width: 100%; text-align: left" :model="addForm" ref="addForm">
          <el-form-item>
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程封面</span>
            <el-upload class="avatar-uploader" action="" style="margin-top: -40px; margin-left: 100px" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img height="210" v-if="imageFile" :src="imageFile" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item width="400px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程价钱</span>
            <el-input style="width: 400px; margin-left: 20px" v-model="addForm.courseTitle" placeholder="请输入课程标题"></el-input>
          </el-form-item>

          <el-form-item width="400px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程介绍</span>
            <el-input style="width: 400px; margin-left: 20px" v-model="addForm.introduction" placeholder="请输入课程介绍" type="textarea"></el-input>
          </el-form-item>

          <el-form-item width="300px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程科目</span>
            <el-select style="width: 200px; margin-left: 20px" v-model="addForm.subjectId" placeholder="请选择科目">
              <el-option v-for="item in subjectArr" :key="item.subjectType" :label="item.subjectType" :value="item.id">
                                       
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item width="300px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">授课教师</span>
            <el-select style="width: 200px; margin-left: 20px" v-model="addForm.teacherId" placeholder="请选择教师">
              <el-option v-for="item in teacherArr" :key="item.tname" :label="item.tname" :value="item.id">
                                       
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-model="addForm.payType" width="400px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px; padding-right: 20px">付费类型</span>
            <template>
              <el-radio v-model="addForm.payType" label="0">免费</el-radio>
              <el-radio v-model="addForm.payType" label="1">付费</el-radio>
            </template>
          </el-form-item>
          <el-form-item v-model="addForm.courseType" width="400px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px; padding-right: 20px">课程类型</span>
            <template>
              <el-radio v-model="addForm.courseType" label="0">视频</el-radio>
              <el-radio v-model="addForm.courseType" label="1">文章</el-radio>
              <el-radio v-model="addForm.courseType" label="2">直播</el-radio>
            </template>
          </el-form-item>
          <el-form-item v-model="addForm.type" width="450px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px; padding-right: 20px">课程所属</span>
            <template>
              <el-radio v-model="addForm.type" label="0">精选课程</el-radio>
              <el-radio v-model="addForm.type" label="1">免费课程</el-radio>
              <el-radio v-model="addForm.type" label="2">微专业</el-radio>
            </template>
          </el-form-item>
        </el-form>
        <el-button style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)" @click="addCourse('addForm')">确 定</el-button>
        <el-button @click="addHandle = false" style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)">取 消</el-button>
      </el-dialog>

      <!-- 修改 -->
      <el-dialog :visible.sync="upHandle" width="30%" style="text-align: left">
        <div slot="title" class="header-title" style="
            text-align: left;
            font-weight: bold;
            color: white;
            font-size: 18px;
            margin-bottom: 10px;
          ">
          课程修改
        </div>
        <el-form stripe style="width: 100%" :model="upForm" ref="upForm">
          <el-form-item width="400px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程封面</span>
            <el-upload class="avatar-uploader" action="" style="margin-top: -40px; margin-left: 100px" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img height="200" v-if="imageFile" :src="imageFile" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item width="400px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程价钱</span>
            <el-input style="width: 400px; margin-left: 20px" v-model="upForm.courseTitle" placeholder="请输入课程标题"></el-input>
          </el-form-item>

          <el-form-item width="400px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程介绍</span>
            <el-input style="width: 400px; margin-left: 20px" v-model="upForm.introduction" placeholder="请输入课程介绍" type="textarea"></el-input>
          </el-form-item>

          <el-form-item width="300px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程科目</span>
            <el-select style="width: 200px; margin-left: 20px" v-model="upForm.subjectId" placeholder="请选择科目">
              <el-option v-for="item in subjectArr" :key="item.subjectType" :label="item.subjectType" :value="item.id">
                                       
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item width="300px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">授课教师</span>
            <el-select style="width: 200px; margin-left: 20px" v-model="upForm.teacherId" placeholder="请选择教师">
              <el-option v-for="item in teacherArr" :key="item.tname" :label="item.tname" :value="item.id">
                                       
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-model="upForm.payType" width="400px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px; padding-right: 20px">付费类型</span>
            <template>
              <el-radio v-model="upForm.payType" label="0">免费</el-radio>
              <el-radio v-model="upForm.payType" label="1">付费</el-radio>
            </template>
          </el-form-item>
          <el-form-item v-model="upForm.courseType" width="400px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px; padding-right: 20px">课程类型</span>
            <template>
              <el-radio v-model="upForm.courseType" label="0">视频</el-radio>
              <el-radio v-model="upForm.courseType" label="1">文章</el-radio>
              <el-radio v-model="upForm.courseType" label="2">直播</el-radio>
            </template>
          </el-form-item>
          <el-form-item v-model="upForm.type" width="450px">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px; padding-right: 20px">课程所属</span>
            <template>
              <el-radio v-model="upForm.type" label="0">精选课程</el-radio>
              <el-radio v-model="upForm.type" label="1">免费课程</el-radio>
              <el-radio v-model="upForm.type" label="2">微专业</el-radio>
            </template>
          </el-form-item>
        </el-form>
        <el-button style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)" @click="upCourse('upForm')">确 定</el-button>
        <el-button @click="upHandle = false" style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)">取 消</el-button>
      </el-dialog>
  </div>
</template>

<script>
import SparkMD5 from "spark-md5";
export default {
  data() {
    return {
      //文件数组
      fileList: [],
      //条数
      total: 0,
      //科目id
      subjectId: "",
      //课程视频数组
      videoArr: [],
      //教师id
      teacherId: "",
      //课程标题
      courseTitle: "",
      //付费类型
      payType: " ",
      //付费类型数组
      payTypeArr: [
        { id: "0", label: "免费" },
        { id: "1", label: "付费" },
      ],
      //课程状态数组
      courseStatusArr: [
        { id: "0", label: "已上架" },
        { id: "1", label: "待上架" },
        { id: "2", label: "未上架" },
      ],
      //课程状态
      courseStatus: " ",
      //课程数组
      courseData: [],
      //课程id
      courseId: "",
      //章节开关
      unit: false,
      //添加章节开关
      unitAdd: false,
      //章节数组
      unitData: [],
      //详细课程开关
      joint: false,
      //章节表单
      unitForm: {
        courseId: "",
      },
      // 表格加载
      loading: true,
      //详细课程数组
      jointData: [],
      //添加详细课程开关
      jointAdd: false,
      //章节id
      unitId: "",
      //详细课程表单
      jointForm: {
        unitId: "",
      },
      //父级科目数组
      subjectArr: [],
      //教师数组
      teacherArr: [],
      //父级课程id
      subjectId: "",
      //添加教师按钮开关
      addHandle: false,
      //修改教师按钮开关
      upHandle: false,
      //id数组
      ids: [],
      //添加教师表单
      addForm: {},
      //修改教师表单
      upForm: {},
      //图片路径回显
      imageFile: "",
      File: File,
      pages: {
        //当前页
        pageNum: 1,
        //每页几条数据
        pageSize: 5,
      },
      fileList: [],
      videoId: 0,
      swithForm: {},
      upJointForm: {},
      upJoint123: false,
    };
  },
  created() {
    this.selectCourse();
  },
  methods: {
    goxiang(row){
      // 跳转并传递参数
      this.$router.push({
        name: 'unit',
        params: {
          id: row.id
        }
      });
    },
    closeUpJoint(){
        this.upJoint123=false
    },
    openUpJoint(row) {
      this.upJointForm = row;
      this.videoId=row.videoId
      this.upJoint123=true
    },
    upJoint() {
      this.upJointForm.videoId=this.videoId
      console.log(this.upJointForm)
      this.$axios.post("http://127.0.0.1:8088/newCourse/upJoint",this.upJointForm)
      .then((res)=>{
        if(res.data.code == 200){
            this.$message.success("操作成功");
            this.upJoint123=false
        }else{
            this.$message.error("操作失败");
        }
      })
    },
    upSwith(row) {
      this.swithForm.id = row.id;
      this.swithForm.jointStatus = row.jointStatus;
      this.$axios
        .post("http://127.0.0.1:8088/newCourse/upSwith", this.swithForm)
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("操作成功");
          } else {
            this.$message.error("操作失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleChange(file, fileList) {},
    async putinMirror(file) {
      const sliceSize = 5 * 1024 * 1024; // 每个文件切片大小定为5MB
      const maxFileSize = 1 * 1024 * 1024 * 1024; // 文件大小限制为最大1个G

      const blob = file.file;
      const fileSize = blob.size; // 文件大小
      const fileName = blob.name; // 文件名
      const totalSlices = Math.ceil(fileSize / sliceSize); // 计算文件切片总数
      //MD5加密计算
      const reader = new FileReader();
      const identifierPrefix = await new Promise((resolve, reject) => {
        reader.onload = () => {
          const spark = new SparkMD5.ArrayBuffer();
          spark.append(reader.result);
          const hash = spark.end();
          resolve(hash); // 使用MD5计算结果作为identifier前缀
        };
        reader.onerror = () => {
          reject(new Error("文件读取错误"));
        };
        reader.readAsArrayBuffer(blob);
      });

      if (fileSize <= maxFileSize) {
        // 循环上传分片
        for (let i = 0; i < totalSlices; i++) {
          const start = i * sliceSize;
          const chunk = blob.slice(
            start,
            Math.min(fileSize, start + sliceSize)
          );
          const formData = new FormData();
          const fileType = fileName.split(".").pop();
          const identifier = identifierPrefix + "-" + (i + 1); // 生成唯一标识符 // 使用原始文件名作为唯一标识符
          formData.append("identifier", identifier);
          formData.append("file", chunk);
          formData.append("chunkNumber", i + 1);
          formData.append("filename", fileName);
          formData.append("totalSize", fileSize);
          formData.append("chunkSize", totalSlices);
          formData.append("totalChunks", chunk.size);
          formData.append("fileType", fileType);

          // 校验分片是否存在
          // const isChunkExist = await this.checkChunkExist(formData);
          // if (isChunkExist === true) {
          //   console.log(`分片 ${i + 1} 已存在，跳过上传`);
          //   continue;
          // } else if (isChunkExist === false) {
          //   console.log(`部分分片已存在，删除不完整的分片，继续上传`);
          //   await this.deleteIncompleteChunks(formData);
          //   // 继续上传下一个分片
          // } else {
          //   console.error(`校验分片失败，取消上传`);
          //   break;
          // }

          const res = await this.uploadExcleAndZip(formData); // 上传分片
          if (res.errCode === 0) {
            setTimeout(() => {
              if (i + 1 === totalSlices) {
                // 上传成功后执行合并操作
                const mergeFormData = new FormData();
                mergeFormData.append("identifier", identifier);
                mergeFormData.append("filename", fileName);
                mergeFormData.append("totalChunks", totalSlices);
                mergeFormData.append("fileType", fileType);
                this.uploadExcleAndZip1(mergeFormData);
                this.$message({
                  message: "上传成功",
                  type: "success",
                });
              }
            }, 1000);
          }
        }
      } else {
        // 文件大小超出最大限制
        this.$message({
          message: "文件大小超出1G",
          type: "error",
        });
      }
    },

    // 校验分片是否存在
    async checkChunkExist(formData) {
      const params = new URLSearchParams(formData);
      const url = `http://127.0.0.1:8088/voide/chunk?${params.toString()}`;
      const response = await this.$axios.get(url).catch((error) => {
        console.error("校验分片失败:", error);
        return null;
      });

      if (response && response.data) {
        const { exist, missingChunks } = response.data;
        if (exist) {
          return true;
        } else {
          await this.deleteIncompleteChunks(formData, missingChunks);
          return false;
        }
      }

      return null;
    },
    //删除不完整的分片
    async deleteIncompleteChunks(identifier, missingChunks) {
      const params = new URLSearchParams();
      params.append("identifier", identifier);
      params.append("missingChunks", missingChunks.join(","));
      // const url = `http://127.0.0.1:8088/voide/deleteChunks?${params.toString()}`;
      const url = `http://127.0.0.1:8088/voide/deleteChunks`;
      try {
        await this.$axios.post(url, params);
      } catch (error) {}
    },

    uploadExcleAndZip(formData) {
      // 上传分片
      return this.$axios
        .post("http://127.0.0.1:8088/voide/chunk", formData)
        .then((res) => {
          return {
            errCode: 0,
          };
        });
    },
    uploadExcleAndZip1(mergeFormData) {
      // 合并分片
      return this.$axios
        .post("http://127.0.0.1:8088/voide/merge", mergeFormData)
        .then((res) => {
          this.videoId = res.data.data;
        })
        .catch((error) => {});
    },
    //修改状态
    upStatusById(row) {
      this.upForm = row;
      this.$axios
        .post("/newCourse/upStatusById", this.upForm)
        .then((res) => {
          if (res.data) {
            this.$message.success("操作成功");
            //关闭添加页面
            this.unitAdd = false;
            //清空表单
            this.upForm = {};
            //刷新
            this.selectCourse();
          } else {
            this.$message.error("操作失败");
          }
        })
        .catch((err) => {});
    },
    //打开章节
    openUnit(row) {
      (this.unit = true), (this.courseId = row.id);
      this.selectUnit();
    },
    //打开添加章节
    openUnitAdd() {
      (this.unitAdd = true), (this.unitForm.courseId = this.courseId);
    },
    //添加章节函数
    addUnit() {
      this.$axios
        .post("/newCourse/insertUnit", this.unitForm)
        .then((res) => {
          if (res.data) {
            this.$message.success("操作成功");
            //关闭添加页面
            this.unitAdd = false;
            //清空表单
            this.unitForm = {};
            //刷新
            this.selectUnit();
          } else {
            this.$message.error("操作失败");
          }
        })
        .catch((err) => {});
    },
    //根据课程全查章节
    selectUnit() {
      this.$axios
        .get("/newCourse/selectUnit", {
          params: {
            courseId: this.courseId,
          },
        })
        .then((res) => {
          if ((res.code = 200)) {
            this.unitData = res.data.data.content;
            this.loading = false;
          }
        })
        .catch((err) => {});
    },
    //打开详细课程
    openJoint(row) {
      this.unitId = row.id;
      this.joint = true;
      this.selectJoint();
    },
    //根据章节全查详细课程
    selectJoint() {
      this.$axios
        .get("/newCourse/selectJoint", {
          params: {
            unitId: this.unitId,
          },
        })
        .then((res) => {
          if ((res.code = 200)) {
            this.jointData = res.data.data.content;
          }
        })
        .catch((err) => {});
    },
    //打开添加详细课程
    openJointAdd(row) {
      this.jointAdd = true;
      this.jointForm.unitId = row.id;
      this.selectVideo();
    },
    //全查视频信息
    selectVideo() {
      this.$axios
        .get("http://127.0.0.1:8088/video/selectAll", {
          params: {},
        })
        .then((res) => {
          if ((res.code = 200)) {
            this.videoArr = res.data.data;
          }
        })
        .catch((err) => {});
    },
    //添加详细课程
    addJoint() {
      this.jointForm.videoId = this.videoId;
      this.$axios
        .post("/newCourse/insertJoint", this.jointForm)
        .then((res) => {
          if (res.data) {
            this.$message.success("添加成功");
            //关闭添加页面
            this.jointAdd = false;
            //清空表单
            this.jointForm = {};
            this.videoId = 0;
            //刷新
            this.selectUnit();
          } else {
            this.$message.error("添加失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //给表格中的性别赋值
    courseStatusFormater: function (row, column) {
      return row.courseStatus == "0"
        ? "已上架"
        : row.courseStatus == "1"
        ? "已下架"
        : row.courseStatus == "2"
        ? "待上架"
        : "错误状态信息，请及时修改";
    },
    payTypeFormater: function (row, column) {
      return row.payType == "0"
        ? "免费"
        : row.payType == "1"
        ? "收费"
        : "请添加收费类型";
    },
    //选中行id存入ids数组
    handleSelectionChange(val) {
      this.ids = val.map((v) => v.id);
    },
    //打开添加页面
    add() {
      this.selectPSubject(), (this.addHandle = true);
    },
    beforeAvatarUpload(file) {
      //上传图片格式
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是JPG/PNG格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过2MB!");
        return false;
      }
      //赋值
      this.fileImage = file;
      this.imageFile = URL.createObjectURL(file);
      //isJPG && isLt2M 自动提交 false 是点击确定后提交
      return false;
    },
    //全查父级科目
    selectPSubject() {
      this.$axios
        .get("/subject/selectAll", { params: {} })
        .then((res) => {
          if ((res.code = 200)) {
            this.subjectArr = res.data.data;
          }
        })
        .catch((err) => {});
    },
    //全查教师
    selectTeacher() {
      this.$axios
        .get("/teacher/selectAll", { params: {} })
        .then((res) => {
          if ((res.code = 200)) {
            this.teacherArr = res.data.data;
          }
        })
        .catch((err) => {});
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 添加文件规则
    beforeFileUpload(file) {
      const isPDF = file.type === "application/pdf";
      const isDOCX =
        file.type ===
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isPDF && !isDOCX) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
        return false;
      }
      this.File = file;
      this.imageUrl = URL.createObjectURL(file);
      return false;
    },
    //添加教师
    addCourse(addForm) {
      // 添加图片信息
      this.$refs[addForm].validate((valid) => {
        if (valid) {
          const formData = new FormData();
          if (this.fileImage) {
            formData.set("imageFile", this.fileImage, this.fileImage.name);
          }
          for (const key in this.addForm) {
            formData.set(key, this.addForm[key]);
          }
          formData.forEach((value, key) => {});

          this.$axios
            .post("/newCourse/insertCourse", formData)
            .then((res) => {
              if (res.data) {
                this.$message.success("添加成功");
                //关闭添加页面
                this.addHandle = false;
                //清空表单
                this.addForm = {};
                //刷新
                this.selectTeacher();
              } else {
                this.$message.error("添加失败");
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //打开修改页面
    openUpCourse(row) {
      //修改表单赋值
      this.upForm = row;
      this.selectPSubject(), this.selectTeacher(), (this.upHandle = true);
      this.imageFile =
        "http://101.43.223.224:8765/image/getImageById?id=" + row.imageId;
    },
    //修改
    upCourse(upForm) {
      // 添加图片信息
      this.$refs[upForm].validate((valid) => {
        if (valid) {
          const formData = new FormData();
          if (this.fileImage) {
            formData.set("imageFile", this.fileImage, this.fileImage.name);
          }
          for (const key in this.upForm) {
            formData.set(key, this.upForm[key]);
          }
          formData.forEach((value, key) => {});
          if (this.upForm.imageId == null) {
            formData.set("imageId", 0);
          }

          this.$axios
            .post("/newCourse/updateCourseById", formData)
            .then((res) => {
              if (res.data) {
                this.$message.success("修改成功");
                //关闭修改页面
                this.upHandle = false;
                //清空表单
                this.upForm = {};

                //刷新
                this.selectCourse();
              } else {
                this.$message.error("修改成功");
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleRemove(file, fileList) {},
    //批量上架
    onShelf() {
      this.$axios
        .post("/newCourse/onShelf", this.ids)
        .then((res) => {
          if (res.data) {
            this.$message.success("批量删除成功");
            //刷新
            this.ids = [];
            this.selectCourse();
          } else {
            this.$message.error("批量删除失败");
          }
        });
    },
    //批量下架
    offShelf() {
      this.$axios
        .post("/newCourse/offShelf", this.ids)
        .then((res) => {
          if (res.data) {
            this.$message.success("批量删除成功");
            //刷新
            this.ids = [];
            this.selectCourse();
          } else {
            this.$message.error("批量删除失败");
          }
        });
    },
    //根据ids批量删除课程
    delBetch() {
      this.$axios
        .post("/newCourse/delByIds", this.ids)
        .then((res) => {
          if (res.data) {
            this.$message.success("批量删除成功");
            //刷新
            this.ids = [];
            this.selectCourse();
          } else {
            this.$message.error("批量删除失败");
          }
        });
    },
    //根据id删除课程
    del(id) {
      this.$axios
        .get("/newCourse/delById?id=" + id)
        .then((res) => {
          if (res.data) {
            this.$message.success("删除成功");
            //刷新
            this.selectCourse();
          } else {
            this.$message.error("删除失败");
          }
        });
    },
    //根据id删除课程
    delUnit(id) {
      this.$axios
        .get("http://127.0.0.1:8088/newCourse/delUnitById?id=" + id)
        .then((res) => {
          if (res.data) {
            this.$message.success("删除成功");
            //刷新
            this.selectUnit();
          } else {
            this.$message.error("删除失败");
          }
        });
    },
    //根据id删除课程
    delOne(id) {
      this.$axios
        .get("http://127.0.0.1:8088/newCourse/delOneById?id=" + id)
        .then((res) => {
          if (res.data) {
            this.$message.success("删除成功");
            //刷新
            this.selectJoint();
          } else {
            this.$message.error("删除失败");
          }
        });
    },
    //全查课程
    selectCourse() {
      this.$axios
        .get("/newCourse/selectCourse", {
          params: {
            subjectId: this.subjectId,
            payType: this.payType,
            courseStatus: this.courseStatus,
            courseTitle: this.courseTitle,
            pageNum: this.pages.pageNum,
            pageSize: this.pages.pageSize,
          },
        })
        .then((res) => {
          if ((res.code = 200)) {
            //教师信息表格赋值
            this.courseData = res.data.data.content;
            this.selectPSubject(), this.selectTeacher(), (this.subjectId = "");
            this.payType = "";
            this.courseStatus = "";
            this.courseTitle = "";
            this.pages.total = res.data.data.totalSize;
          }
        })
        .catch((err) => {});
    },
    //分页
    handleSizeChange(val) {
      this.pages.pageSize = val;
      this.selectCourse();
    },
    handleCurrentChange(val) {
      this.pages.pageNum = val;
      this.selectCourse();
    },
    handleOpen(key, keyPath) {},
    handleClose(key, keyPath) {},
    openadd() {
      this.updateadd = true;
    },
    handleAvatarSuccess() {},
  },
};
</script>

<style>
.video-wrapper {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 比例：将高度设为宽度的 56.25% */
}

.video-wrapper video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
div {
  font-family: 微软雅黑;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 336px;
  height: 210px;
  line-height: 210px;
  text-align: center;
}
.avatar {
  width: 336px;
  height: 210px;
  display: block;
}
.el-dialog__header {
  background: rgb(93, 142, 255);
  text-align: center;
}
.el-dialog__headerbtn .el-dialog__close {
  color: #ffffff;
}
.el-empty__image {
  width: 60px;
}
</style>
